# Copyright (c) 2022, hzmes and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document
from frappe.utils import getdate, today


class SRMHandboardRequest(Document):

	def autoname(self):
		if self.billno:
			self.name = self.billno


	def before_insert(self):
		if not self.billno:
			current_billno = "SBSQ"
			current_billno += "".join(today().split("-"))
			series = frappe.db.get_value('SRM Naming Series',
								{'doctype_name': self.doctype, 'date': today()},
								['name', 'current_series'], as_dict=True)
			if series:
				current_billno += str(series.current_series).zfill(3)
			else:
				frappe.get_doc({'doctype': 'SRM Naming Series', 'doctype_name': self.doctype, 'date': today()}).insert(ignore_permissions=True)
				current_billno += "001"
			self.billno = current_billno
			frappe.db.set_value('SRM Naming Series', series.name, 'current_series', series.current_series + 1)


# 传递单据类型及单据编号查找日志
@frappe.whitelist()
def get_workflow_info(doctype, reference_name):
	dt = frappe.db.sql(
		f"""SELECT co.creation, wo.state, wo.action, co.content, user.full_name
			from `tabComment` co, 
				(SELECT wp.document_type, wc.state, wc.action, wc.next_state FROM `tabWorkflow` wp JOIN `tabWorkflow Transition` wc ON wp.name = wc.parent) wo,
				`tabUser` user
			WHERE wo.document_type = co.reference_doctype AND wo.next_state = co.content AND co.comment_email = user.name
			AND co.comment_type = 'Workflow'
			AND wo.document_type = '{doctype}'
			AND co.reference_name = '{reference_name}'
			ORDER BY co.creation DESC;
		""", as_dict=True
	)

	return dt
